package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.AddUser;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.GetCode;
import com.heima.model.user.pojos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {



    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * app端登录
     *
     * @param loginDto@return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.正常登录（手机号+密码登录）
        if (!StringUtils.isBlank(loginDto.getPhone()) && !StringUtils.isBlank(loginDto.getPassword())) {
            //1.1查询用户
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }

            //1.2 比对密码
            String salt = apUser.getSalt();
            String pswd = loginDto.getPassword();
            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            if (!pswd.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            log.info("集合数据 {}", map);
            return ResponseResult.okResult(map);
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }

    }

    /**
     * 注册账户
     *&& phone.contains("")
     * @param phone
     */
    @Override
    public ResponseResult register(String phone) {

        int length = phone.length();
        if (length == 11 && phone.contains("") ) {
           // ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "输入的格式有误请从新输入");

        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
        if (apUser == null) {


            String str = UUID.randomUUID().toString();
            String codes = str.trim().replaceAll("-", "");
            String code = codes.substring(codes.length() - 4);
            log.info("code= {}", code);

            //调用工具类生成验证码
            SendSms.sendMsg(phone, code);

            redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("phone",phone);
            }
        }

          return   ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"输入格式错误");

    }

    /**
     * 验证码校验
     *
     * @param getCode
     */
    @Override
    public ResponseResult getcode(GetCode getCode) {
        //获取手机号
        String phone = getCode.getPhone();

        //获取验证码
        String code = getCode.getCode();

        //获取redis中的验证码
        Object redisCode = redisTemplate.opsForValue().get(phone);

        //进行验证码的比对（页面提交的验证码和redis中保存的验证码比对）
        if (redisCode!=null && redisCode.equals(code)){
            //如果能够比对成功
             return    ResponseResult.okResult(200,"验证码校验成功");
        }else{
            //验证码失效
          return   ResponseResult.errorResult(AppHttpCodeEnum.SIG_TIMEOUT,"验证码过期");
        }


    }

    /**
     * 创建账户和密码
     *
     * @param addUser
     * @return
     */
    @Override
    public ResponseResult adduser(AddUser addUser) {
        //获取账户名
        String name = addUser.getName();

        //获取密码
        String password = addUser.getPassword();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String md5pswd = DigestUtils.md5DigestAsHex((uuid + password).getBytes());

        //获取手机号
        String phone = (String) redisTemplate.opsForValue().get("phone");
        if (phone!=null){
            //保存成功删除redis缓存中的手机号
            redisTemplate.delete("phone");
        }
        Date date = new Date();
        //封装对象
        ApUser apUser = new ApUser();
        apUser.setPassword(md5pswd);
        apUser.setPhone(phone);
        apUser.setSalt(password);
        apUser.setName(name);
        apUser.setCreatedTime(date);
        //保存数据库

        save(apUser);


        return ResponseResult.okResult(200,"成功啦哟");
    }
}